package com.totoro.controller;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.totoro.pojo.*;
import com.totoro.service.*;
import com.totoro.utils.ReturnFormat;
import com.totoro.utils.TotoroUtils;
import lombok.SneakyThrows;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author TOTORO
 * @date 2021/8/6 13:25
 */
@Controller
@RequestMapping("/seller_logic")
public class SellerController {

    private final SellerService sellerService;
    private final ProductService productService;
    private final AttributeService attributeService;
    private final CategoryService categoryService;
    final ShopService shopService;

    public SellerController(SellerService sellerService, ProductService productService, AttributeService attributeService, CategoryService categoryService, ShopService shopService) {
        this.sellerService = sellerService;
        this.productService = productService;
        this.attributeService = attributeService;
        this.categoryService = categoryService;
        this.shopService = shopService;
    }

    @SneakyThrows
    @RequestMapping(value = "/findRender", method = RequestMethod.POST)
    @ResponseBody
    public String findRender(@RequestBody JsonNode jsonNode, HttpSession session){
        User user = (User) session.getAttribute("user");
        Seller seller = sellerService.findSellerIdByUserId(user.getUserId());
        Shop shop = shopService.findShopBySlid(seller.getId());

//        User user = (User) session.getAttribute("user");
        // 获取所有的过滤条件
        String productTitle = jsonNode.get("productTitle").asText();
        int[] productIds = null;
        // 判断用户的id分隔符
        String[] pIds = null;
        // 如果不是空，判断是否有该三种分隔符
        if(!jsonNode.get("productId").asText().equals("") && jsonNode.get("productId").asText() != null){
            if(jsonNode.get("productId").asText().contains(",")){
                pIds = jsonNode.get("productId").asText().split(",");
            } else if(jsonNode.get("productId").asText().contains(" ")){
                pIds = jsonNode.get("productId").asText().split(" ");
            } else if(jsonNode.get("productId").asText().contains("，")) {
                pIds = jsonNode.get("productId").asText().split("，");
                // 否则 没有分割
            } else {
                pIds = new String[]{TotoroUtils.getStrIncludeNumber(jsonNode.get("productId").asText())};
            }
            productIds = Arrays.stream(pIds).mapToInt(Integer::parseInt).toArray();
        }
        Double productMinPrice = jsonNode.get("productMinPrice").asDouble();
        Double productMaxPrice = jsonNode.get("productMaxPrice").asDouble();
        Integer categoryId = jsonNode.get("categoryId").asInt();
        Integer shopCategoryId = jsonNode.get("shopCategoryId").asInt();
        Integer productMinSale = jsonNode.get("productMinSale").asInt();
        Integer productMaxSale = jsonNode.get("productMaxSale").asInt();
        Integer productStatus = jsonNode.get("productStatus").asInt();
        Integer productNowPage = jsonNode.get("productNowPage").asInt();
        BuyProductTerm buyProductTerm = new BuyProductTerm(productTitle, productIds, productMinPrice, productMaxPrice, categoryId, shopCategoryId, productMinSale, productMaxSale, productStatus, productNowPage, true, seller.getId(), null, null, 0);
        List<Product> productList = sellerService.termFindSellerBuyBaby(buyProductTerm);
        // 查一遍未分页的
        buyProductTerm.setIsPagination(false);
        List<Product> notPagination = sellerService.termFindSellerBuyBaby(buyProductTerm);
        List<Object> jsonList = new ArrayList<>();
        jsonList.add(notPagination.size());
        jsonList.add(productList);
        ObjectMapper objectMapper = new ObjectMapper();
        return objectMapper.writeValueAsString(jsonList);
    }

    /**
     * 找所有商品
     * @return
     */
    @RequestMapping("/findAllSellerProduct")
    @SneakyThrows
    @ResponseBody
    public String findAllSellerProduct(HttpSession session){
        User user = (User) session.getAttribute("user");
        Seller seller = sellerService.findSellerIdByUserId(user.getUserId());
        Shop shop = shopService.findShopBySlid(seller.getId());

        List<Product> productList = sellerService.directFindSellerBuyBaby(seller.getId());
        ObjectMapper objectMapper = new ObjectMapper();
        return objectMapper.writeValueAsString(productList);
    }

    @RequestMapping(value = "/updateProductName", method = RequestMethod.POST)
    @ResponseBody
    public String updateProductName(@RequestBody JsonNode jsonNode){
        Integer productId = jsonNode.get("productId").asInt();
        String productName = jsonNode.get("productName").asText();
        Integer itMethod = jsonNode.get("itMethod").asInt();
        Integer tr = sellerService.updateProductName(productId, productName, itMethod);
        if(tr>0){
            return ReturnFormat.retData("编辑标题成功", true);
        }
        return ReturnFormat.retData("系统繁忙，请稍后再试", false);
    }

    @RequestMapping("/getProductSkus")
    @ResponseBody
    public String findProductSkus(@RequestBody JsonNode jsonNode){
        Integer productId = jsonNode.get("productId").asInt();
        List<ProductSpecs> skus = attributeService.findProductSkusById(productId);
        return ReturnFormat.retData(skus, true);
    }

    /**
     * 修改商品Sku属性
     * @param jsonNode
     * @return
     */
    @RequestMapping("/updateProductSkuAttr")
    @ResponseBody
    public String updateProductSkuAttr(@RequestBody JsonNode jsonNode){
        JsonNode skuAttr = jsonNode.get("skus");
        int productStock = 0;
        Double[] productPrice = new Double[skuAttr.size()];
        for (int i = 0; i < skuAttr.size(); i++) {
            ProductSpecs productSpecs = new ProductSpecs();
            productSpecs.setId(skuAttr.get(i).get("id").asInt());
            productSpecs.setProductPrice(skuAttr.get(i).get("productPrice").asDouble());
            productSpecs.setProductStock(skuAttr.get(i).get("productStock").asInt());
            attributeService.updateProductSkuAttr(productSpecs);
            productStock+=skuAttr.get(i).get("productStock").asInt();
            productPrice[i] = skuAttr.get(i).get("productPrice").asDouble();
        }
        // 修改商品的属性会影响商品实质，所以需要进而修改商品
        Product product = productService.findProductById(skuAttr.get(0).get("pid").asInt());
        // 获得最小价格 (当前价格)
        product.setBeforePrice(product.getNowPrice());
        product.setNowPrice(jsonNode.get("price").asDouble());
        product.setProductCount(productStock);
        productService.updateProductPriceAndStockByPid(product);
        return ReturnFormat.retData("编辑商品成功", true);
    }

    /**
     * 修改商品上下架状态
     * @param jsonNode
     * @return
     */
    @RequestMapping("/updateProductStatus")
    @ResponseBody
    public String updateProductStatus(@RequestBody JsonNode jsonNode){
        // 拿到所有需要改变状态的商品，进行循环
        JsonNode root = jsonNode.get("products");
        boolean isUpdate = jsonNode.get("isUpdate").asBoolean();
        Integer status = jsonNode.get("status").asInt();
        boolean isDelete = jsonNode.get("isDelete").asBoolean();
        Integer deleteStatus = jsonNode.get("deleteStatus").asInt();
        for (int i = 0; i < root.size(); i++) {
            Integer productId = root.get(i).get("productId").asInt();
            productService.updateProductStatusByPid(productId, isUpdate, status, isDelete, deleteStatus);
            // 如果是删除，则需要添加删除时间
            if(isDelete){
                productService.updateProductDeleteTime(productId);
            }
        }
        return ReturnFormat.retData("成功", true);
    }

    /**
     * 查找一级类别
     * @param jsonNode
     * @return
     */
    @SneakyThrows
    @RequestMapping("/findCategoryByCid")
    @ResponseBody
    public String findCategoryByCid(@RequestBody JsonNode jsonNode){
        String id = jsonNode.get("categoryIds").toString();
        String[] ids = id.substring(1, id.length()-1).split(",");
        // 轉換成鍵值對的類別
        Set<Category> categories = new HashSet<>();

        for (int i = 0; i < ids.length; i++) {
            Category category = categoryService.byIdFindCategory(Integer.parseInt(ids[i]));
            categories.add(category);
        }
        return ReturnFormat.retData(categories, true);
    }

    /**
     * 根据产品id查找产品最新信息
     * @param jsonNode
     * @return
     */
    @RequestMapping("findOneProduct")
    @ResponseBody
    public String findOneProduct(@RequestBody JsonNode jsonNode){
        int pid = jsonNode.get("productId").asInt();
        return ReturnFormat.retData(productService.findProductById(pid), true);
    }
    /**
     * 查询店铺所有分类  注意，需要活得店铺ID ****************************************************************
     * @param session
     * @return
     */
    @RequestMapping(value = "/findAllShopCategory", method = RequestMethod.POST)
    @SneakyThrows
    @ResponseBody
    public String findAllShopCategory(HttpSession session){
        User user = (User) session.getAttribute("user");
        Seller seller = sellerService.findSellerIdByUserId(user.getUserId());
        Shop shop = shopService.findShopBySlid(seller.getId());
        List<ShopCategory> shopCategories = shopService.findAllShopCategory(shop.getId());
        return ReturnFormat.retData(shopCategories, true);
    }

    /**
     * 添加商品至分类
     * @param jsonNode
     * @return
     */
    @RequestMapping(value = "/productGotoCategory", method = RequestMethod.POST)
    @ResponseBody
    public String productGotoCategory(@RequestBody JsonNode jsonNode){
        int pid = jsonNode.get("productId").asInt();
        int scid = jsonNode.get("scid").asInt();
        shopService.addProductGoToCategory(scid, pid);
        return ReturnFormat.retData("添加成功", true);
    }

    /**
     * 添加新分类，注意，需要活得店铺ID ****************************************************************
     * @param jsonNode
     * @return
     */
    @RequestMapping(value = "/addShopCategory", method = RequestMethod.POST)
    @ResponseBody
    public String addShopCategory(@RequestBody JsonNode jsonNode, HttpSession session){
        User user = (User) session.getAttribute("user");
        Seller seller = sellerService.findSellerIdByUserId(user.getUserId());
        Shop shop = shopService.findShopBySlid(seller.getId());

        String categoryName = jsonNode.get("categoryName").asText();
        ShopCategory shopCategory = new ShopCategory();
        shopCategory.setSid(shop.getId());
        shopCategory.setScName(categoryName);
        // 进行比对，看看这个卖家是否已经有了这个分类名称
        int length = shopService.checkShopCategoryName(shopCategory);
        if(length > 0){
            return ReturnFormat.retData("添加失败，已存在该分类！", false);
        } else{
            shopService.addShopCategory(categoryName, shop.getId());
            return ReturnFormat.retData("添加成功", true);
        }
    }

    /**
     * 删除店铺分类
     * @param jsonNode
     * @return
     */
    @RequestMapping(value = "/deleteShopCategory", method = RequestMethod.POST)
    @ResponseBody
    public String deleteShopCategory(@RequestBody JsonNode jsonNode){
        int scId = jsonNode.get("shopCategoryId").asInt();
        shopService.deleteShopCategory(scId);
        // 将该分类下的商品改为无分类
        shopService.updateCategoryProductEmpty(scId);
        return ReturnFormat.retData("删除成功！", true);
    }

    /** 商品回收站 -------------------------- */
    /**
     * 查询删除的商品
     * @return
     */
    @SneakyThrows
    @RequestMapping("/getDeleteProducts")
    @ResponseBody
    public String getDeleteProducts(@RequestBody JsonNode jsonNode, HttpSession session){
        User user = (User) session.getAttribute("user");
        Seller seller = sellerService.findSellerIdByUserId(user.getUserId());
        Shop shop = shopService.findShopBySlid(seller.getId());

        String productTitle = jsonNode.get("productTitle").asText();
        JsonNode productDeleteTime = jsonNode.get("productPublicTime");
        Integer productNowPage = jsonNode.get("productNowPage").asInt();
        Integer babyType = jsonNode.get("babyType").asInt();
        BuyProductTerm buyProductTerm = new BuyProductTerm();
        buyProductTerm.setProductNowPage(productNowPage);
        buyProductTerm.setIsPagination(true);
        // 用户是查询删除的 还是历史的
        buyProductTerm.setDeleteOrHistory(babyType);
        // 如果用户选择了时间
        if(productDeleteTime.get(0) !=null) {
            buyProductTerm.setPublicMinTime(productDeleteTime.get(0).asText());
            buyProductTerm.setPublicMaxTime(productDeleteTime.get(1).asText());
        }
        buyProductTerm.setSlid(seller.getId());
        buyProductTerm.setProductTitle(productTitle);
//        buyProductTerm.setPublicTime(productDeleteTime);
        List<Product> products = sellerService.termFindSellerDeleteBaby(buyProductTerm);
        // 获取未分页的页面总数
        buyProductTerm.setIsPagination(false);
        int pageAllSize = sellerService.termFindSellerDeleteBaby(buyProductTerm).size();
        // 将总页数和数据放入集合，序列化JSON
        List<Object> list = new ArrayList<>();
        list.add(pageAllSize);
        list.add(products);
        return ReturnFormat.retData(list, true);
    }

    /**
     * 回复产品
     * @param jsonNode
     * @return
     */
    @RequestMapping("/recoverProduct")
    @ResponseBody
    public String recoverProduct(@RequestBody JsonNode jsonNode){
        JsonNode products = jsonNode.get("products");
        Integer reasonId = jsonNode.get("reasonId").asInt();
        for (int i = 0; i < products.size(); i++) {
            Integer productId = products.get(i).get("productId").asInt();
            // 恢复之前，先获取该商品的删除时间，如果在七天内删除过，则失败

            productService.addProductRecover(reasonId, productId);
        }
        return ReturnFormat.retData("success", true);
    }


    /**
     * 我需要申请卖家
     * @param shopName
     * @param session
     * @return
     */
    @RequestMapping("/INeedToApplySeller")
    public String applySeller(@RequestParam("shopName") String shopName, HttpSession session){
        User user = (User) session.getAttribute("user");
        sellerService.addApplySeller(user.getUserId(), shopName);
        return "redirect:/seller/applySeller.htm";
    }

    /**
     * 重复提交申请卖家
     * @param session
     * @return
     */
    @RequestMapping("/againApplySeller")
    @SneakyThrows
    public String againApplySeller(HttpSession session){
        User user = (User) session.getAttribute("user");
        ApplySeller applySeller = sellerService.findUserApplySellerStatus(user.getUserId());
        long sevenDay = 86400000 * 7;
        if(System.currentTimeMillis() - new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(applySeller.getUpdateTime()).getTime() >= sevenDay) {
            sellerService.deleteApplySeller(user.getUserId());
        }
        return "redirect:/seller/applySeller.htm";
    }

//    以下为店铺管理-----------------------------------

    @RequestMapping("/getSellerInfo")
    @ResponseBody
    public String getSellerInfo(HttpSession session){
        User user = (User) session.getAttribute("user");
        Seller seller = sellerService.findSellerIdByUserId(user.getUserId());
        return ReturnFormat.retData(seller, true);
    }

    /**
     * 修改店铺主要资料
     * @param jsonNode
     * @param session
     * @return
     */
    @RequestMapping("/submitShopPrimaryDetail")
    @ResponseBody
    public String updateShopPrimaryDetail(@RequestBody JsonNode jsonNode, HttpSession session){
        User user = (User) session.getAttribute("user");
        String shopName = jsonNode.get("name").asText();
        String address = jsonNode.get("address").asText();
        String addressCode = jsonNode.get("addressCode").asText();
        String detail = jsonNode.get("detail").asText();
        // 转换成对象
        Shop shop = new Shop();
        shop.setId(shopService.findShopBySlid(user.getSeller().getId()).getId());
        shop.setShopName(shopName);
        shop.setAddress(address);
        shop.setAddressCode(addressCode);
        shop.setShopInfo(detail);
        System.out.println(shop);
        sellerService.updateShopPrimaryInfo(shop);

        return ReturnFormat.retData("修改成功", true);
    }
    /**
     * 上传店铺的头像
     * @param session
     * @param file
     * @param request
     * @return
     */
    @SneakyThrows
    @ResponseBody
    @RequestMapping(value = "/uploadShopHead", method = RequestMethod.POST)
    public String uploadShopHead(HttpSession session, @RequestParam("file") MultipartFile file, HttpServletRequest request){
        User user = (User) session.getAttribute("user");
        String fileName = file.getOriginalFilename();
        // 适用UUID生成新的图片名称和路径，防止图片重复
        String uploadPath = request.getSession().getServletContext().getRealPath("/")+"static\\img\\seller\\shop\\";
        // 生成新的名字
        String newFileName = UUID.randomUUID() + fileName;
        // 封装上传文件位置的全路径
        File targetFile = new File(uploadPath, newFileName);
        file.transferTo(targetFile);
        // 添加头像至库中
        Shop shop = shopService.findShopBySlid(user.getSeller().getId());
        sellerService.updateShopHeadByShopId(shop.getId(), newFileName);
        return ReturnFormat.retData("上传成功", true);
    }

    /**
     * 删除店铺头像
     * @param session
     * @param request
     * @return
     */
    @RequestMapping("/deleteShopHead")
    @ResponseBody
    public String deleteShopHead(HttpSession session, HttpServletRequest request){
        User user = (User) session.getAttribute("user");
        // 获得店铺，删除头像
        Shop shop = shopService.findShopBySlid(user.getSeller().getId());
        // 先从文件中删除
        String imagePath = request.getSession().getServletContext().getRealPath("/")+"static\\img\\seller\\shop\\"+shop.getShopHead();
        File file = new File(imagePath);
        if(file.exists()){
            file.delete();
        }
        // 从数据库删除
        sellerService.updateShopHeadByShopId(shop.getId(), "");
        return ReturnFormat.retData("删除成功", true);
    }

    /**
     * 查找店铺所有资料
     * @param session
     * @return
     */
    @ResponseBody
    @RequestMapping("/findShop")
    public String findShopHead(HttpSession session){
        User user = (User) session.getAttribute("user");
        // 获得店铺
        Shop shop = shopService.findShopBySlid(user.getSeller().getId());
        return ReturnFormat.retData(shop, true);
    }

    /**
     * 上传店铺招牌图
     * @param session
     * @param file
     * @param request
     * @return
     */
    @SneakyThrows
    @RequestMapping("/uploadShopPrimaryImage")
    @ResponseBody
    public String uploadShopPrimaryImage(HttpSession session, @RequestParam("file") MultipartFile file, HttpServletRequest request){
        String fileName = file.getOriginalFilename();
        // 适用UUID生成新的图片名称和路径，防止图片重复
        String uploadPath = request.getSession().getServletContext().getRealPath("/")+"static\\img\\seller\\shop\\";
        // 生成新的名字
        String newFileName = UUID.randomUUID() + fileName;
        // 封装上传文件位置的全路径
        File targetFile = new File(uploadPath, newFileName);
        file.transferTo(targetFile);
        User user = (User) session.getAttribute("user");
        // 获得店铺
        Shop shop = shopService.findShopBySlid(user.getSeller().getId());
        sellerService.updateShopPrimaryImage(shop.getId(), newFileName);
        return ReturnFormat.retData("上传成功", true);
    }

    /**
     * 删除店铺招牌图
     * @param session
     * @param request
     * @return
     */
    @RequestMapping("/deleteShopPrimaryImage")
    @ResponseBody
    public String deleteShopPrimaryImage(HttpSession session,  HttpServletRequest request){
        User user = (User) session.getAttribute("user");
        // 获得店铺，删除头像
        Shop shop = shopService.findShopBySlid(user.getSeller().getId());
        // 先从文件中删除
        String imagePath = request.getSession().getServletContext().getRealPath("/")+"static\\img\\seller\\shop\\"+shop.getShopImage();
        File file = new File(imagePath);
        if(file.exists()){
            file.delete();
        }
        // 从数据库删除
        sellerService.updateShopPrimaryImage(shop.getId(), "");
        return ReturnFormat.retData("删除成功", true);
    }

    /**
     * 修改店铺背景颜色
     * @param jsonNode
     * @param session
     * @return
     */
    @RequestMapping("/updateShopCategoryBackgroundColor")
    @ResponseBody
    public String updateShopCateyBackgroundgoryColor(@RequestBody JsonNode jsonNode, HttpSession session){
        String color = jsonNode.get("color").asText();
        if("null".equals(color)){
            color = "";
        }
        User user = (User) session.getAttribute("user");
        // 获得店铺
        Shop shop = shopService.findShopBySlid(user.getSeller().getId());
        sellerService.updateShopCategoryBackgroundColor(shop.getId(), color);
        return ReturnFormat.retData("修改成功", true);
    }

    /**
     * 修改店铺前景颜色
     * @param jsonNode
     * @param session
     * @return
     */
    @RequestMapping("/updateShopCategoryForegroundColor")
    @ResponseBody
    public String updateShopCategoryForegroundColor(@RequestBody JsonNode jsonNode, HttpSession session){
        String color = jsonNode.get("color").asText();
        if("null".equals(color)){
            color = "";
        }
        User user = (User) session.getAttribute("user");
        // 获得店铺
        Shop shop = shopService.findShopBySlid(user.getSeller().getId());
        sellerService.updateShopCategoryForegroundColor(shop.getId(), color);
        return ReturnFormat.retData("修改成功", true);
    }

    /**
     * 添加一张店铺轮播图
     * @param file
     * @param session
     * @param request
     * @return
     */
    @RequestMapping("/addShopSwitchImage")
    @ResponseBody
    @SneakyThrows
    public String addShopSwitchImage(@RequestParam("file") MultipartFile file, HttpSession session, HttpServletRequest request){
        String fileName = file.getOriginalFilename();
        // 适用UUID生成新的图片名称和路径，防止图片重复
        String uploadPath = request.getSession().getServletContext().getRealPath("/")+"static/img/seller/shop/";
        // 生成新的名字
        String newFileName = UUID.randomUUID() + fileName;
        // 封装上传文件位置的全路径
        File targetFile = new File(uploadPath, newFileName);
        file.transferTo(targetFile);
        User user = (User) session.getAttribute("user");
        // 获得店铺
        Shop shop = shopService.findShopBySlid(user.getSeller().getId());
        ShopSwitchImage shopSwitchImage = new ShopSwitchImage("/static/img/seller/shop/"+newFileName, shop.getId());
        sellerService.addShopSwitchImage(shopSwitchImage);
        return ReturnFormat.retData("上传成功", true);
    }

    /**
     * 删除一张店铺轮播图
     * @param jsonNode
     * @param session
     * @param request
     * @return
     */
    @RequestMapping("/deleteShopSwitchImage")
    @ResponseBody
    public String deleteShopSwitchImage(@RequestBody JsonNode jsonNode,  HttpSession session,  HttpServletRequest request){
        User user = (User) session.getAttribute("user");
        // 获得店铺id
        Shop shop = shopService.findShopBySlid(user.getSeller().getId());
        // 获得轮播图路径
        String ip = "/static/img/seller/shop/"+jsonNode.get("fileName").asText();
        // 先从文件中删除
        String imagePath = request.getSession().getServletContext().getRealPath("/")+ip;
        File file = new File(imagePath);
        if(file.exists()){
            file.delete();
        }
        // 从数据库删除
        sellerService.deleteShopSwitchImage(new ShopSwitchImage(ip, shop.getId()));
        return ReturnFormat.retData("删除成功", true);
    }

    /**
     * 获得某个店铺所有轮播
     * @param session
     * @return
     */
    @RequestMapping("/findAllShopSwitchImage")
    @ResponseBody
    public String findAllShopSwitchImage(HttpSession session){
        User user = (User) session.getAttribute("user");
        // 获得店铺id
        Shop shop = shopService.findShopBySlid(user.getSeller().getId());
        List<ShopSwitchImage> shopSwitchImages = shopService.findShopSwitchImage(shop.getId(), null);
        return ReturnFormat.retData(shopSwitchImages, true);
    }
}
